package com.example.module_word.search.viewmodel

import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.ToastUtils
import com.example.module_word.room.CourseDataBase
import com.example.module_word.search.entity.DictionaryResult
import com.fenghuajueli.libbasecoreui.baseswitch.PublicFunction
import com.example.module_word.net.TianXingManage
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

class DictionariesViewMode : ViewModel() {

    val dao = CourseDataBase.instance.courseDao()

    val dictionaryResult = MutableStateFlow<DictionaryResult?>(null)

    val word = mutableStateOf("")

    fun wordChange(msg: String) {
        word.value = msg
        if (word.value.isEmpty()) {
            //清除上次查询记录
            dictionaryResult.value = null
        }
    }

    fun  getDictionaryResult() = TianXingManage.apply {
        if (!PublicFunction.checkCanUsedByPosition(3,true)){
            return@apply
        }
        if (word.value.isEmpty()) {
            ToastUtils.showShort("请输入英语单词~")
            return@apply
        }
        getKey {
            viewModelScope.launch(Dispatchers.IO) {
                runCatching {
                    dao.getSearchHistoryListByWord(word.value).let {
                        if (it == null) {
                            getDictionaryEntity(word.value).collectLatest {
                                val newContent = it.content.replace("|", "\n").replace(":", ": ")
                                    .replace(",", ", ")
                                dictionaryResult.value = it.copy(content = newContent)
                                dao.insertSearchHistoryList(
                                    it.copy(
                                        content = newContent,
                                        updateTime = System.currentTimeMillis()
                                    )
                                )
                            }
                        } else {
                            dictionaryResult.value = it
                            dao.updateSearchHistoryList(it.copy(updateTime = System.currentTimeMillis()))
                        }
                    }
                }.onFailure {
                    ToastUtils.showShort("网络连接失败,请检查网络")
                }
            }
        }
    }

    fun deleteSearchHistoryList() = viewModelScope.launch(Dispatchers.Default) {
        dao.deleteSearchHistoryList()
    }
}